const path = require('path');
const fs = require('fs-extra');
const express = require('express');
const multer = require('multer');
const { idOcr, documentOcr } = require('../ai');
const { runTasksInParallel } = require('../handy');
const { getImageManifest } = require('../manifest');

const router = express.Router();
const upload = multer({ storage: multer.memoryStorage() });

const OCR_TYPE_ID = 1;
const OCR_TYPE_DOCUMENT = 2;

router.post('/ocr', upload.none(), async (req, res) => {
    console.log('ocr');
    const uuid = req.body.uuid;
    if (!uuid) {
        res.json({ code: 400, message: 'uuid不能为空' });
        return;
    }
    const zipFileHash = req.body.zipFileHash;
    if (!zipFileHash) {
        res.json({ code: 400, message: 'zipFileHash不能为空' });
        return;
    }
    let pdfFileHash = req.body.pdfFileHash;
    if (!pdfFileHash) {
        res.json({ code: 400, message: 'pdfFileHash不能为空' });
        return;
    }
    let ocrType = req.body.ocrType;
    if (!ocrType) {
        res.json({ code: 400, message: 'ocrType不能为空' });
        return;
    }
    const zipFileDir = path.join(
        global.__rootDir,
        'uploads',
        uuid,
        zipFileHash
    );
    const ocrResults = [];
    const pdfFileDir = path.join(zipFileDir, pdfFileHash);
    let manifest = getImageManifest({ zipFileHash, pdfFileHash, uuid });
    const imageFileNames = fs
        .readdirSync(pdfFileDir)
        .filter((e) => /(.*)\.png|jpg|jpeg/.test(e));
    const tasks = [];
    for (const imageFileName of imageFileNames) {
        tasks.push(createTask.bind(null, { imageFileName }));
    }
    
    async function createTask({ imageFileName }) {
        const imageFilePath = path.join(pdfFileDir, imageFileName);
        const ext = path.extname(imageFilePath);
        const baseName = path.basename(imageFilePath, ext);
        const resultFilePath = path.join(pdfFileDir, baseName + '.json');
        if (fs.existsSync(resultFilePath)) {
            console.log('read result from disk: ' + resultFilePath);
            const result = fs.readFileSync(resultFilePath, {
                encoding: 'utf-8',
            });
            ocrResults.push(JSON.parse(result));
            return;
        }
        const imageList = manifest.imageList;
        const imageInfo = imageList.find((e) => e.imageName === imageFileName);
        if (!imageInfo) {
            console.error('在图片OCR过程中：' + imageFilePath);
            throw new Error('未生成图片 manifest信息');
        }
        let result;
        if (ocrType == OCR_TYPE_DOCUMENT) {
            result = await documentOcr({
                imageFileId: imageInfo.fileId,
                imageFileName,
            });
        } else if (ocrType == OCR_TYPE_ID) {
            result = await idOcr({
                imageFileId: imageInfo.fileId,
                imageFileName,
            });
        } else {
            throw new Error('Not support ocr type yet.');
        }
        if (!result) {
            res.json({
                code: 500,
                message: 'ocr 失败：' + imageFileName,
            });
            return;
        }
        fs.writeFileSync(resultFilePath, JSON.stringify(result, null, 4), {
            encoding: 'utf-8',
        });
        ocrResults.push(result);
    }
    await runTasksInParallel(tasks, 2);
    return res.json({
        code: 200,
        message: 'ocr成功',
        result: {
            ocrResults,
        },
    });
});

module.exports = router;
